package org.inspur;

import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang3.StringUtils;
import org.hyperledger.fabric.contract.Context;
import org.hyperledger.fabric.contract.ContractInterface;
import org.hyperledger.fabric.contract.annotation.*;
import org.hyperledger.fabric.shim.ChaincodeException;
import org.hyperledger.fabric.shim.ChaincodeStub;
import org.inspur.entity.FlowEntity;
import org.inspur.entity.WmsEntity;

import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author lijiahao
 * @date 2024/6/28
 */
@Contract(
        name = "WmsContract",
        info = @Info(
                title = "Wms contract",
                description = "The hyperlegendary Wms contract",
                version = "0.0.1-SNAPSHOT",
                license = @License(
                        name = "Apache 2.0 License",
                        url = "http://www.apache.org/licenses/LICENSE-2.0.html"),
                contact = @Contact(
                        email = "wms@inspur.com",
                        name = "wms",
                        url = "https://hyperledger.example.com")))
@Default
public class WmsContract implements ContractInterface {

    @Transaction
    public void initLedger(final Context ctx) {

    }

    @Transaction
    public WmsEntity queryWms(final Context ctx, final String key) {
        ChaincodeStub stub = ctx.getStub();

        String stringState = stub.getStringState(key);
        if (StringUtils.isEmpty(stringState)) {
            throw new ChaincodeException(String.format("WMS %s does not exist", key));
        }

        return JSON.parseObject(stringState, WmsEntity.class);
    }

    @Transaction
    public String createWms(final Context ctx, final String key, String userId, String userName, String dataList) {
        ChaincodeStub stub = ctx.getStub();

        FlowEntity flowEntity = new FlowEntity(userId, userName, dateTimeFormatToTimestamp(stub.getTxTimestamp().toString()), stub.getTxId(), dataList);

        String[] strings = new String[1];
        strings[0] = JSON.toJSONString(flowEntity);

        WmsEntity wmsEntity = new WmsEntity();
        wmsEntity.setData(strings);

        String stringState = stub.getStringState(key);
        if (StringUtils.isNotEmpty(stringState)) {
            wmsEntity = JSON.parseObject(stringState, WmsEntity.class);
            wmsEntity.setData(appendStr(wmsEntity.getData(), JSON.toJSONString(flowEntity)));
//            throw new ChaincodeException(String.format("WMS %s already exists", key));
        }
        String json = JSON.toJSONString(wmsEntity);
        stub.putStringState(key, json);
        stub.setEvent("createWmsEvent", StringUtils.getBytes(json, StandardCharsets.UTF_8));

        return stub.getTxId();
    }

    @Transaction
    public void deleteWms(final Context ctx, final String key) {
        ChaincodeStub stub = ctx.getStub();

        String stringState = stub.getStringState(key);
        if (StringUtils.isEmpty(stringState)) {
            throw new ChaincodeException(String.format("WMS %s does not exist", key));
        }
        stub.delState(key);
    }

//    @Transaction
//    public WmsEntity updateWms(final Context ctx, final String key, String materialName, String materialCode, String parentId, String payload) {
//        ChaincodeStub stub = ctx.getStub();
//
//        String personState = stub.getStringState(key);
//        if (StringUtils.isEmpty(personState)) {
//            throw new ChaincodeException(String.format("WMS %s does not exist", key));
//        }
//
//        WmsEntity wmsEntity = new WmsEntity(materialName, materialCode, parentId, payload);
//        String newPersonState = JSON.toJSONString(wmsEntity);
//        stub.putStringState(key, newPersonState);
//
//        return wmsEntity;
//    }

    /**
     * 数组末尾添加元素
     *
     * @param data 数据列表
     * @param el   数据
     * @return {@link String[] }
     * @author lijiahao
     * @date 2024/07/01
     */
    private String[] appendStr(String[] data, String el) {
        String[] str = new String[data.length + 1];
        System.arraycopy(data, 0, str, 0, data.length);
        str[str.length - 1] = el;
        return str;
    }

    private String dateTimeFormatToString(String time) {
        if (StringUtils.isEmpty(time)) {
            return null;
        }
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(time);
        LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();
        // 转换为Date
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return localDateTime.format(formatter);
    }

    private String dateTimeFormatToTimestamp(String time) {
        if (StringUtils.isEmpty(time)) {
            return null;
        }
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(time);
        Instant instant = zonedDateTime.toInstant();
        return String.valueOf(instant.toEpochMilli());
    }
}